<?php

class M_check_verification Extends MY_Model
{

	/*
		validate verification link and creates login credentials for student
	*/
	public function check_and_create_login_credentials($id,$auth)
	{
		$sql = 'SELECT enrollment_transaction_code,
					   mustverify,
					   e_profile_id,
					   e_student_id,
					   concat(profiles.lastname," , ",profiles.firstname," ",profiles.middlename) as fullname,
					   profiles.email
				FROM enrollments
				LEFT JOIN profiles ON e_profile_id = profiles.profile_id
				WHERE enrollment_transaction_code = ?
				AND e_id = ?
				AND verified = 0
				LIMIT 1 ';
		$query = $this->db->query($sql,array($auth,$id));
		
		if($query->num_rows() >= 1)
		{
			$result = $query->row();
			
			// check if time verify is expired
			if(time() >= $result->mustverify)
			{
				$link = site_url('confirm/resend');
				$log['stat'] =  FALSE;
				$log['log'] = 'This validation link is already expired. <a href="'.$link.'" class="btn btn-success">Resend Validation</a>';
				return (object)$log;
			}else
			{
				// update verified statust to true
				$this->db->set('verified',1)->where('e_id',$id)->update('enrollments');
				if($this->db->affected_rows() >= 1)
				{
					//generate student password
					$this->load->model('M_users');
					$password_generate = substr(md5(rand(100,999)),0,8);
					$data_user['username'] = $result->e_student_id;
					$data_user['hashed_password'] = $this->M_users->hash_password($password_generate);
					$data_user['userType'] = 'student';
					$data_user['userStatus'] = 'active';
					$data_user['created_at'] = NOW;
					
					//insert the data to user table
					$this->db->insert('users',$data_user);
					// get last inserted ID
					$student_user_id = $this->db->insert_id();
					
					//if insert was successfull
					if($this->db->affected_rows() >= 1)
					{
						//insert last inserted ID from the users table to the profiles table
						$this->db->set('user_id',$student_user_id)->where('profile_id',$result->e_profile_id)->update('profiles');
						if($this->db->affected_rows() >= 1)
						{
							$log['password'] = $password_generate;
							$log['username'] = $result->e_student_id;
							$log['fullname'] = $result->fullname;
							$log['email'] = $result->email;
							
							$log['stat'] =  TRUE;
							$log['log'] = 'Your enrollment was successfully verified. Kindly refer to your email for your account details. Thank you';
							return (object)$log;
						}else{
							//failed in updating profile user_id
							$this->db->delete('users',$student_user_id);
							$log['stat'] =  FALSE;
							$log['log'] = 'Unable to update profile user id';
							return (object)$log;
						}
					}else{
						//insert fail return false
						$log['stat'] =  FALSE;
						$log['log'] = 'Unable to insert users to database';
						return (object)$log;
					}
				}else{
					$log['stat'] =  FALSE;
					$log['log'] = 'Unable to verify user';
					return (object)$log;
				}
			}
		}else
		{
			$log['stat'] =  FALSE;
			$log['log'] = 'Unable to get code';
			return (object)$log;
		}
	}
	
	
	/*
		validate confirmation link without creating a login credentials for the student
	*/
	public function check($id,$code)
	{
		$sql = 'SELECT enrollment_transaction_code,
						   mustverify,
						   e_profile_id,
						   e_student_id,
						   concat(profiles.lastname," , ",profiles.firstname," ",profiles.middlename) as fullname,
						   profiles.email
					FROM enrollments
					LEFT JOIN profiles ON e_profile_id = profiles.profile_id
					WHERE enrollment_transaction_code = ?
					AND e_id = ?
					AND verified = 0
					LIMIT 1 ';
					
		$query = $this->db->query($sql,array($code,$id));
	
		if($query->num_rows() >= 1)
		{
			$result = $query->row();
			// check if confirmation link is expired
			if(time() >= $result->mustverify)
			{
				$message ='Sorry, The verification link you have supplied to us is already expired. Please regenerate a new confirmation link.';
				$message .='<a href="'.site_url('confirm/resend').'" class="btn btn-success">Resend Confirmation Link</a>';
				$log['stat'] =  FALSE;
				$log['log'] = $message;
				return (object)$log;
			}else{
				//confirmation link not yet expired, update verification status
				$this->db->set('verified',1)->where('e_id',$id)->update('enrollments');
				
				if($this->db->affected_rows() >=1)
				{
					$message ='Confirmation successfully verified. Please Check your email address for further instruction.';
					$log['fullname'] = $result->fullname;
					$log['email'] = $result->email;
					$log['stat'] =  TRUE;
					$log['log'] = $message;
					return (object)$log;
				}else{
					$message ='THe system has encountered an error while trying to validate your confirmation link.';
					$message .='Pleae try to re-click the confirmation link or regenerate a new confirmation link';
					$message .='<a href="'.site_url('confirm/resend').'" class="btn btn-success">Regenerate and Resend Confirmation Link</a>';
					$log['stat'] =  FALSE;
					$log['log'] = $message;
					return (object)$log;
				}
			}
		}else{
			$message ='Sorry,The system has encountered an error while trying to retrieve your confirmation code.';
			$message .='Please try clicking the verification link again or try to regenerate a new confirmation link';
			$message .='<a href="'.site_url('confirm/resend').'" class="btn btn-success">Resend Confirmation Link</a>';
			$log['stat'] =  FALSE;
			$log['log'] = $message;
			return (object)$log;
		}
	}
	
	public function resend_confirmation_code($x = FALSE)
	{
		if($x !== FALSE)
		{
			$select_email = "SELECT email,e_id,user_id,firstname,middlename,lastname,profile_id
							 FROM profiles
							 LEFT JOIN enrollments ON enrollments.e_profile_id = profiles.profile_id
							 WHERE email = ?
							 AND enrollments.verified = 0 ";
			$query = $this->db->query($select_email,array($x));
			
			
			
			if($query->num_rows() >= 1)
			{
				$r = $query->row();
				$conf_code = substr(base64_encode(sha1(time().rand(10,99).md5(time().rand(100,200)))),0,15);
				
				$this->db->set('enrollment_transaction_code',$conf_code)
						 ->set('mustverify',(time()*60))
						 ->set('verified',0)
						 ->where('e_id',$r->e_id)
						 ->where('e_profile_id',$r->profile_id)
						 ->update('enrollments');
				
				if($this->db->affected_rows() >= 1)
				{
					$log['id'] = $r->e_id;
					$log['etc'] = $conf_code;
					$log['email'] = $r->email;
					$log['fullname'] = ucwords(strtolower($r->lastname.' '.$r->firstname.' '.$r->middlename[0].'.'));
					$log['stat'] = TRUE;
					$log['log'] = 'Updated confirmation code';
					return (object)$log;
				}else{
					$log['stat'] = FALSE;
					$log['log']  = 'System was unable to generate confirmation code, Try again later';
					return (object)$log;
				}
			}else{
				$log['stat'] = FALSE;
				$log['log']  = 'Email Address Not Found';
				return (object)$log;
			}

		}else{
			return FALSE;
		}
	}
}